package main

import (
	"../crawler"
	"fmt"
	"log"
	"net/http"
)

func main() {
	//爬虫接口
	http.HandleFunc("/crawl", crawl)

	log.Fatal(http.ListenAndServe("localhost:8010", nil))
}

func crawl(w http.ResponseWriter, req *http.Request) {
	err := req.ParseForm()
	if err != nil {
		log.Println(err)
		Fprint(w, "error")
		return
	}
	var platform = getFormValue("platform", req)
	var url = getFormValue("url", req)
	if platform == "1688" {
		response := crawler.Crawl1688(url)
		Fprint(w, response)
		return
	}
	Fprint(w, "nil")
}

func Fprint(w http.ResponseWriter, response string) {
	_, err := fmt.Fprintf(w, response)
	if err != nil {
		log.Println(err)
	}
}

func getFormValue(p string, req *http.Request) string {
	v, f := req.Form[p]
	if !f {
		log.Println("..接收参数异常:" + p + "  ")
		return ""
	}
	return v[0]
}
